import updateManager from './common/updateManager';

App({
  onLaunch: function () {},
  onShow: function () {
    updateManager();
    // this.checkLoginUserSocket();
    // //判断是否登录 连接socket
    // this.globalData.socketClientTimer = setInterval(() => {
    //   // 定时器---检查用户登录状态，并决定是否开启socket
    //   this.checkLoginUserSocket();
    // }, 30000);
  },
  globalData: {
    userInfo: {},
    socketUrl: null, // socketUrl
    timeout: 10000, // 延迟
    socketHeartTimer: null,
    callback: function () {}, // socket连接回调函数
    socketClientTimer: null, // socket连接定时器
    isSocketConnect: false, // 当前socket是否连接
  },

  // 检查用户登录状态，并决定是否开启socket
  checkLoginUserSocket() {
    this.globalData.userInfo = wx.getStorageSync('userInfo') || null;
    if (this.globalData.userInfo != null && JSON.stringify(this.globalData.userInfo) != '{}') {
      //登录状态下调用连接socket 且判断是否已经连接socket
      if (!this.globalData.isSocketConnect) {
        //未连接，去连接socket
        this.connectSocketFunciton();
      }
    } else {
      // 未登录情况下清楚websocket定时器
      this.closeSocketFunction();
    }
  },
  // 小程序进入后台
  onHide() {
    // 关闭全局socket状态连接定时器
    clearInterval(this.globalData.socketClientTimer);
    // 关闭socket
    this.closeSocketFunction();
  },

  //小程序连接socket
  connectSocketFunciton() {
    var that = this;
    var socketUrl = `ws://localhost:8019/websocket/${that.globalData.userInfo.id}`;
    wx.connectSocket({
      url: socketUrl,
      success: (res) => {
        console.log(res);
        // 标识socket已连接
        that.globalData.isSocketConnect = true;
        // 初始化连接监听
        that.initEventHandler();
        //清除链接
        this.closeSocketFunction();
      },
      fail: (fail) => {},
    });
  },
  // 绑定监听
  initEventHandler() {
    var that = this;
    // socket连接开启
    wx.onSocketOpen((result) => {
      // 开启心跳
      that.startHeart();
    });
    // socket连接关闭
    wx.onSocketClose((res) => {
      if (that.globalData.isSocketConnect) {
        that.connectSocketFunciton();
      }
    });
    // 接收socket消息
    wx.onSocketMessage((res) => {
      console.log('onSocketMessage', res);
      //第一次消息如果为init就绑定uid
      // var data = JSON.parse(res.data)
      //这里data可以根据后端返回的数据做一些处理 根据自己的需求做出对应的处理
      // 全局socket接收消息的方法回调
      that.globalData.callback(res);
    });
  },
  //发送心跳
  startHeart() {
    if (this.globalData.isSocketConnect) {
      this.globalData.socketHeartTimer = setInterval(() => {
        wx.sendSocketMessage({
          data: 'heartBath',
          success: function (res) {},
          fail: function (res) {},
        });
      }, 45 * 1000);
    } else {
      clearTimeout(this.globalData.socketHeartTimer);
    }
  },
  //此页面关闭socket和定时器的函数
  closeSocketFunction: function () {
    if (this.globalData.isSocketConnect) {
      // 标识socket已断开
      this.globalData.isSocketConnect = false;
      // 关闭socket连接
      wx.closeSocket();
      // 关闭socket心跳定时器
      clearInterval(this.globalData.socketHeartTimer);
    }
  },
});
